﻿using System.Collections;
using Castle.DynamicProxy;
using Crow.Library.DatabaseLayer;
using Crow.Library.DatabaseLayer.DataAttributes;

namespace Crow.Library.Interceptors.DatabaseInceptors.DbOperations
{
    internal class UpdateOperator : DbOperationBase
    {
        public override void Execute(IInvocation invocation, DbAttributeBase attribute)
        {
            var db = DatabaseHelper.GetDatabase();
            db.Connection.Open();
            try
            {
                var result = 0;
                for (int i = 0; i < invocation.Arguments.Length; i++)
                {
                    object arg = invocation.Arguments[i];
                    if (arg is IEnumerable)
                    {
                        foreach (object argItem in (arg as IEnumerable))
                        {
                            result = db.Update(argItem);
                        }
                    }
                    else
                    {
                        result = db.Update(arg);
                    }
                }

                SetInvocationResult(invocation, result);
            }
            finally
            {
                db.Connection.Close();
            }
        }
    }
}